<?php
/**
 * vanephp web framework
 * 文件日志服务类
 *
 * @author aray <ofree@qq.com>
 * @link http://www.vanephp.com/s
 * @copyright Copyright &copy; 2010 aray
 * @license http://www.vanephp.com/license
 * @package log
 */

if ( ! defined ( 'INVANE' ) )
	exit ( '!' );

/**
 * 文件日志服务类
 * @author aray
 *
 */
class vane_log_file {
	private $logFilename = 'access.log';
	private static $logFilePath = null;
	/**
	 * 初始化日志服务
	 */
	public function initLoger ( ) {
		if ( self::$logFilePath === null ) {
			self::$logFilePath = config::get ( 'log_dir' );
			mkdirs ( self::$logFilePath );
			self::$logFilePath .= DS . $this->logFilename;
			// 创建日志文件
			if ( ! file_exists ( self::$logFilePath ) ) {
				$fp = fopen ( self::$logFilePath, 'w' );
				fclose ( $fp );
			}
		}
	}
	/**
	 * 记录日志
	 * @param string $key		日志名称
	 * @param string $val		日志内容
	 */
	public function set ( $key, $val ) {
		if ( config::get ( 'log_enable' ) == 'true' ) {
			$this->initLoger ( );
			
			if ( ! in_array ( $key, config::get ( 'log_type' ) ) ) {
			
			} else {
				static $logMaxSize = null;
				if ( $logMaxSize == null ) {
					$logMaxSize = ( int ) config::get ( 'log_maxsize' );
					$logMaxSize = $logMaxSize >= 102400 ? $logMaxSize : 102400;
				}
				// 文件大小
				$fsize = filesize ( self::$logFilePath );
				if ( $fsize >= $logMaxSize ) {
					$pathinfo = pathinfo ( self::$logFilePath );
					rename ( self::$logFilePath, $pathinfo['dirname'] . DS . $pathinfo['filename'] . date ( '.Ymd_his.' ) . $pathinfo['extension'] );
				}
				
				$log = URI . "\r\n";
				$log .= sprintf ( '%s		%s		%s', date::now ( ), $key, $val );
				
				$fcontent = safe_file_get_contents ( self::$logFilePath );
				$fcontent .= ($fcontent == '' ? $log : "\r\n" . $log);
				safe_file_put_contents ( self::$logFilePath, $fcontent );
			}
		}
	}
}